<template>
	<view class="container">
		<view class="search-navi-bar" :style="{ paddingTop: safeArea + 'px' }">
			<uni-search-bar
				class="search-bar"
				@confirm="onSearch"
				:focus="true"
				v-model="keyword"
				@focus="onFocus"
				@input="onInput"
				@cancel="cancelSearch"
				@clear="clearKeyword"
				radius="100"
			></uni-search-bar>
		</view>

		<!-- 搜索建议 -->
		<view class="suggestions" v-if="showSuggestions && suggestions.length > 0">
			<view class="suggestion-item" v-for="(item, index) in suggestions" :key="index" @click="selectSuggestion(item)">
				<uni-icons type="search" size="14" color="#999" class="mr-2"></uni-icons>
				<text>{{ item }}</text>
			</view>
		</view>

		<!-- 搜索历史 -->
		<view class="history-container" v-if="showHistory">
			<view class="history-header">
				<text class="title">搜索历史</text>
				<view class="clear-btn" @click="clearHistory" v-if="searchHistory.length > 0">
					<uni-icons type="trash" size="14" color="#999"></uni-icons>
					<text class="ml-1">清空历史</text>
				</view>
			</view>
			<view class="history-tags" v-if="searchHistory.length > 0">
				<view class="tag" v-for="(item, index) in searchHistory" :key="index" @click="selectHistory(item)">
					<text>{{ item }}</text>
				</view>
			</view>
			<view class="empty-history" v-else>
				<text>暂无搜索历史</text>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="result-container" v-if="showResult">
			<!-- 加载状态 -->
			<view class="loading" v-if="isLoading">
				<uni-load-more
					status="loading"
					:contentText="{
						loading: '加载中...',
						end: '没有更多数据了',
						error: '加载失败，请重试'
					}"
				></uni-load-more>
			</view>

			<view v-if="Object.keys(searchResult).length > 0" class="search-results">
				<view
					class="search-group"
					v-if="searchResult.group && searchResult.group.length > 0"
					v-for="(group, index) in searchResult.group"
					:key="group.groupId"
					@click="joinGroup(group)"
				>
					<view class="result-title">
						<uni-icons type="staff-filled" color="#55aaff" size="26"></uni-icons>
						<text class="type-txt">公共群组</text>
					</view>

					<view class="">
						<text class="group-lable">群名：</text>
						<text>{{ group.groupName }}</text>
						<text class="group-lable">群介绍：</text>
						<text>{{ group.signature }}</text>
					</view>
				</view>
				<view
					class="search-product"
					v-if="searchResult.product && searchResult.product.length > 0"
					v-for="(product, index) in searchResult.product"
					:key="product.productId"
					@click="toShop(product.productId)"
				>
					<view class="result-title">
						<uni-icons type="gift" color="#55aaff" size="26"></uni-icons>
						<text class="type-txt">商品信息</text>
					</view>

					<view class="">
						<text>{{ product.productName }}</text>
						<text>{{}}</text>
					</view>
				</view>
				<view
					class="search-message"
					v-if="searchResult.message && searchResult.message.length > 0"
					v-for="(msg, index) in searchResult.message"
					:key="msg.timestamp"
					@click="toChat(msg)"
				>
					<view class="result-title">
						<uni-icons type="chat" color="#55aaff" size="26"></uni-icons>
						<text class="type-txt">公共信息</text>
					</view>

					<view class="search-message-content">
						<view v-if="msg.nicPic.url" class="img-box">
							<image class="img" :src="msg.nicPic.url" mode="scaleToFill"></image>
						</view>
						<avatar-fallback v-show="!msg.nicPic.url" :name="msg.nicName || msg.sendUserId"></avatar-fallback>
						<view class="">
							<text>{{ msg.nicName }}:</text>
							<text class="msg">{{ msg.content.text }}</text>
						</view>
					</view>
				</view>
				<view
					class="search-address"
					v-if="searchResult.address && searchResult.address.length > 0"
					v-for="(address, index) in searchResult.address"
					:key="index"
					@click="toMap(address.location)"
				>
					<view class="result-title">
						<uni-icons type="location" size="26" color="#55aaff"></uni-icons>
						<text class="type-txt">地理位置</text>
						<text class="type-txt">地址关键词：</text>
						<text class="type-txt">{{ keyword }}</text>
					</view>
					<view class="address-content">
						<text class="type-txt">详细地址：</text>
						<text>{{ address.province + address.city + address.district + address.street }}</text>
					</view>
				</view>
			</view>

			<!-- 空结果状态 -->
			<view class="empty-result" v-else-if="searchResult.length === 0">
				<image src="/static/images/empty-search.png" mode="aspectFit"></image>
				<text class="mt-3">没有找到与"{{ keyword }}"相关的商品</text>
				<button class="retry-btn" type="default" @click="clearKeyword">重新搜索</button>
			</view>
		</view>
	</view>
</template>

<script>
import GroupAvatarVue from '../../components/GroupAvatar.vue';
import AvatarFallback from '../../components/AvatarFallback.vue';
import { getGridCode } from '../../utils/getSurroundingGrids';
import setToTarget from '../../utils/setTarget';
const group = uniCloud.importObject('groupManager');
export default {
	components: {
		GroupAvatarVue,
		AvatarFallback
	},
	data() {
		return {
			keyword: '',
			searchHistory: [],
			suggestions: [],
			products: [],
			isLoading: false,
			showHistory: true,
			showResult: true,
			showSuggestions: false,
			timer: null,
			searchResult: {},
			category: '',
			minPrice: 0,
			maxPrice: 999999,
			page: 1,
			safeArea: 0,
			pageSize: 20,
			groupId: '',
			keyboardListen: null,
			keyboardHeight: 0
		};
	},
	onLoad() {
		const res = uni.getSystemInfoSync();
		this.safeArea = res.safeArea.top;
		this.loadSearchHistory();
	},
	methods: {
		onFocus() {
			if (this.keyword) {
				this.showHistory = false;
				this.showResult = false;
				this.showSuggestions = true;
				this.getSuggestions(this.keyword);
			} else {
				this.showHistory = true;
				this.showResult = false;
				this.showSuggestions = false;
			}
		},
		// 输入事件处理
		onInput(e) {
			console.log('11111', e);
			// 正确获取输入值：e.detail.value（UniApp 组件统一的参数格式）
			this.keyword = e;

			if (this.keyword) {
				this.showHistory = false;
				this.showResult = false;
				this.showSuggestions = true;

				// 防抖处理（保留原逻辑，修复参数后生效）
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.getSuggestions(this.keyword);
				}, 300);
			} else {
				this.showHistory = true;
				this.showResult = false;
				this.showSuggestions = false;
			}
		},
		loadSearchHistory() {
			try {
				const history = uni.getStorageSync('search_history');
				if (history) {
					this.searchHistory = JSON.parse(history);
				} else {
					uni.showToast({
						title: '无记录'
					});
				}
			} catch (e) {
				console.error('Failed to load search history:', e);
			}
		},
		selectHistory(keyword) {
			this.keyword = keyword;
			this.onSearch();
		},
		selectSuggestion(suggestion) {
			this.keyword = suggestion;
			this.onSearch();
		},
		clearKeyword() {
			this.keyword = '';
			this.showHistory = true;
			this.showResult = false;
			this.showSuggestions = false;
		},
		// 取消搜索
		cancelSearch() {
			uni.navigateBack();
		},
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清除搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.searchHistory = [];
						try {
							uni.removeStorageSync('search_history');
						} catch (e) {
							console.error('Failed to clear search history:', e);
						}
					}
				}
			});
		},
		async onSearch() {
			if (!this.keyword.trim()) return;

			this.showHistory = false;
			this.showSuggestions = false;
			this.showResult = true;
			this.isLoading = true;

			try {
				// 1. 保存搜索历史
				this.saveSearchHistory(this.keyword);
				// 2. 异步获取结果（等待完成）

				this.isLoading = false;
			} catch (e) {
				this.isLoading = false;
				uni.showToast({ title: '搜索失败，请重试', icon: 'none' });
				console.error('搜索错误:', e);
			}
		},
		saveSearchHistory(keyword) {
			const pureKeyword = keyword.trim(); // 去除前后空格
			if (!pureKeyword) return;

			// 去重：忽略空格差异，不区分大小写（可选，根据需求调整）
			this.searchHistory = this.searchHistory.filter((item) => item.trim().toLowerCase() !== pureKeyword.toLowerCase());

			this.searchHistory.unshift(pureKeyword); // 存入处理后的关键词
			if (this.searchHistory.length > 10) {
				this.searchHistory = this.searchHistory.slice(0, 10);
			}

			try {
				uni.setStorageSync('search_history', JSON.stringify(this.searchHistory));
			} catch (e) {
				console.error('Failed to save search history:', e);
			}
		},
		// 获取搜索建议
		getSuggestions(keyword) {
			this.isLoading = true;
			uniCloud
				.callFunction({
					name: 'getSuggestions',
					data: { keyword: keyword,location:this.$store.state.msg.location}
				})
				.then((res) => {
					this.showResult = true;
					console.log(res);
					this.searchResult = { ...res.result.data };
					this.suggestions = res.result.data;
					this.isLoading = false;
				})
				.catch((e) => {
					this.isLoading = false;
					console.log(e);
				});
		},
		async joinGroup(groupInfo) {
			try {
				const res = await group.applyJoin(this.$store.state.msg.user.userId, { groupId: groupInfo.groupId, userLocation: this.$store.state.msg.location });
				uni.showToast({
					title: res.message,
					position: 'center',
					duration: 2000
				});
				if (res.code === -2) {
					let queryParam = {};
					queryParam.id = groupInfo.groupId;
					queryParam.type = 'group';
					this.$store.commit('msg/SET_queryParam', queryParam);
					setToTarget('group', { groupId: groupInfo.groupId, groupName: groupInfo.groupName });
					uni.navigateTo({
						url: '/pages/messages/messages'
					});
				}
			} catch (e) {
				console.warn(e);
			}
		},
		toChat(msg) {
			uni.navigateTo({
				url: `/pages/friend/friend?id=${msg.sendUserId}`
			});
		},
		toShop(productId) {
			uni.navigateTo({
				url: `/pages/shopMain/shopMain?id=${productId}`
			});
		},
		toMap(loc) {
		
			const location = { longitude:Number(loc.split(',')[0]) , latitude: Number(loc.split(',')[1])  };

			const grid = getGridCode(location);
			let queryParam = {};
			queryParam.id = grid;
			queryParam.location = location;
			queryParam.type = 'public';
			this.$store.commit('msg/SET_queryParam', queryParam);
			this.$store.commit('msg/SET_isFly', true);
			if (!location.longitude || !location.latitude) {
				console.error('无定位坐标');
				return;
			}
			setToTarget('public', { targetName: this.$store.state.msg.address.address });
			this.$store.commit('msg/SET_location', location);
			uni.navigateTo({
				url: '/pages/main/main'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.search-navi-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	background-color: #55aaff;
}
.container {
	background-color: #eaeaea;
	min-height: 100vh;
	min-width: 100vw;
	padding-top: 160rpx;
}
.search-results {
	display: flex;
	flex-direction: column;
	padding: 20rpx;
	gap: 15rpx;
	.type-txt {
		font-size: 24rpx;
		color: #007aff;
	}
	.search-address,
	.search-group,
	.search-message,
	.search-product {
		display: flex;
		flex-direction: column;
		border-radius: 8rpx;
		background-color: #fff;
		margin-bottom: 10px; // 添加底部外边距保证间距
		padding: 10px; // 内边距保持内容不贴边
	}
	.search-address {
	}
	.address-content {
		display: flex;
		align-items: center;
	}
	.group-content {
		display: flex;
		align-items: center;
	}
	.result-title {
		display: flex;
		align-items: center;
		gap: 15rpx;
	}
	.group-lable {
		font-size: 24rpx;
		color: #007aff;
		font-weight: 600;
		margin-left: 20rpx;
	}
	.search-message {
		display: flex;
		gap: 10rpx;
		.img-box {
			width: 80rpx;
			height: 80rpx;
			border-radius: 8rpx;
			overflow: hidden;
			.img {
				width: 80rpx;
				height: 80rpx;
			}
		}
		.msg {
			color: #999;
		}
	}
	.search-message-content {
		display: flex;
	}
}

/* 搜索栏 */
.search-bar {
	display: flex;
	align-items: center;
	padding: 10px 15px;
	background-color: #55aaff;
	border-bottom: 1px solid #eee;

	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		height: 32px;
		padding: 0 10px;
		background-color: #f5f5f5;
		border-radius: 16px;

		.search-icon {
			margin-right: 5px;
		}

		input {
			flex: 1;
			height: 100%;
			font-size: 14px;
			color: #333;

			.placeholder {
				color: #999;
			}
		}

		.clear-icon {
			padding: 3px;
			cursor: pointer;
		}
	}

	.cancel-btn {
		width: 50px;
		text-align: center;
		color: #007aff;
		font-size: 14px;
		cursor: pointer;
	}
}

/* 搜索建议 */
.suggestions {
	background-color: #fff;
	border-bottom: 1px solid #eee;

	.suggestion-item {
		display: flex;
		align-items: center;
		padding: 10px 15px;
		font-size: 14px;
		color: #333;
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		&:hover {
			background-color: #f8f8f8;
		}
	}
}

/* 搜索历史 */
.history-container {
	padding: 15px;
	background-color: #fff;

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 30px;

		.title {
			font-size: 14px;
			color: #333;
			font-weight: 500;
		}

		.clear-btn {
			display: flex;
			align-items: center;
			color: #999;
			font-size: 12px;
			cursor: pointer;
		}
	}

	.history-tags {
		display: flex;
		flex-wrap: wrap;
		padding-top: 10px;

		.tag {
			padding: 5px 12px;
			margin-right: 10px;
			margin-bottom: 10px;
			background-color: #f5f5f5;
			border-radius: 15px;
			font-size: 12px;
			color: #666;
			cursor: pointer;

			&:hover {
				background-color: #eee;
			}
		}
	}

	.empty-history {
		padding: 20px 0;
		text-align: center;
		color: #999;
		font-size: 13px;
	}
}

/* 搜索结果 */
.result-container {
	padding: 10px;

	.loading {
		padding: 20px 0;
		text-align: center;
	}

	.empty-result {
		padding: 40px 0;
		text-align: center;

		image {
			width: 120px;
			height: 120px;
			opacity: 0.6;
		}

		text {
			display: block;
			margin-top: 15px;
			color: #999;
			font-size: 14px;
		}

		.retry-btn {
			width: 120px;
			height: 32px;
			line-height: 32px;
			margin-top: 20px;
			padding: 0;
			font-size: 14px;
			background-color: #ff4d4f;
			color: #fff;
			border-radius: 16px;
		}
	}
}
</style>
